package com.xinling.modules.chat.controller;

import com.xinling.modules.chat.model.dto.ChatMessage;
import com.xinling.modules.chat.service.ChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

@Controller
public class ChatController {
    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);

    private final ChatService chatService;
    private final SimpMessagingTemplate messagingTemplate;

    public ChatController(ChatService chatService, SimpMessagingTemplate messagingTemplate) {
        this.chatService = chatService;
        this.messagingTemplate = messagingTemplate;
    }

    @MessageMapping("/chat")
    public void handleMessage(@Payload ChatMessage message) {
        logger.info("收到新消息 - 类型: {}, 内容: {}", message.getType(), message.getContent());
        try {
            // 处理消息
            ChatMessage response = chatService.handleMessage(message);
            logger.info("消息处理完成，准备发送响应 - 类型: {}", response.getType());

            // 发送响应
            messagingTemplate.convertAndSend("/topic/chat", response);
            logger.info("响应发送成功");
        } catch (Exception e) {
            logger.error("消息处理失败: {}", e.getMessage(), e);
            // 发送错误响应
            ChatMessage errorResponse = new ChatMessage();
            errorResponse.setType("error");
            errorResponse.setContent("处理消息时发生错误: " + e.getMessage());
            errorResponse.setTimestamp(System.currentTimeMillis());
            messagingTemplate.convertAndSend("/topic/chat", errorResponse);
            logger.error("已发送错误响应给客户端");
        }
    }
} 